﻿<template>
  <a-modal
    :title="(type==='modify'?'修改':'新增')+'采购收货'"
    width="90vw"
    :visible="visible"
    dialogClass="zero-modal"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <div class="purchase-receive-modal-content">
        <div class="form-view">
          <a-form :form="form">
            <a-row>
              <a-col :md="12" :sm="24">
                <a-form-item label="单据号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input disabled v-decorator="['purchaseReceiveOrderOrderNo',{rules:[{required:true,message:'单据号不可为空！'}]}]" />
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24" v-if="type==='add'">
                <a-form-item label="采购单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select style="width: 100%" v-decorator="['purchaseOrderNo',{rules:[{required:true,message:'请选择采购单号！'}]}]" placeholder="请选择...">
                    <a-select-option v-for="(item,index) in selectOptions.purchaseOrders" :key="index" :value="item.purchaseOrderNo">{{ item.purchaseOrderNo }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="12" :sm="24" v-else>
                <a-form-item label="采购单号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input disabled v-decorator="['purchaseOrderNo']" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="action-view">
          <a-button type="primary" icon="plus" :disabled="type==='modify'" @click="openChoose">
            添加物料
          </a-button>
        </div>
        <div class="list-view" ref="listWrapper">
          <!-- 注意scroll.x的值 -->
          <template v-if="th">
            <a-table v-if="type==='modify'" :data-source="list" :columns="columnsEdit" :rowKey="tableKey" :pagination="false" :scroll="{x:1100,y:th}">
              <template slot="index" slot-scope="text,record,index">{{index+1}}</template>
              <template slot="inputCell" slot-scope="text,record,index">
                <a-input-number v-model="record.receiveQuantity" :min="0" />
              </template>
              <span slot="unitTyleSlot" slot-scope="text">{{ 'unit_type' | dictType(text) }}</span>
            </a-table>
            <a-table v-else :data-source="list" :columns="columnsAdd" :rowKey="tableKey" :pagination="false" :scroll="{x:1100,y:th}">
              <template slot="index" slot-scope="text,record,index">{{index+1}}</template>
              <template slot="action" slot-scope="text,record,index">
                <a-button type="danger" size="small" @click.stop="cancelListItem(index)">删除</a-button>
              </template>
              <span slot="unitTyleSlot" slot-scope="text">{{ 'unit_type' | dictType(text) }}</span>
            </a-table>
          </template>
          
        </div>
      </div>
    </a-spin>
    
    <choose-modal :visible.sync="chooseVisible" :query-order-no="chooseOrderNo" @callback="chooseBack" />
    
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" @click="onSubmit" :disabled="!list.length">确认</a-button>
    </template>
  </a-modal>
</template>

<script>
  import {
    PurchaseReceiveOrderAdd,
    GetBillNumber,
    GetPurchaseOrders,
    PurchaseReceiveOrderDetailPage,
    PurchaseReceiveOrderEditDetailNumber
  } from '@/api/modular/main/PurchaseReceiveOrderManage'
  import ChooseModal from './chooseMaterials.vue'
  export default {
    components:{ChooseModal},
    props:{
      type:{
        type:String,
        default:''
      }
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        },
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this),
        selectOptions:{
          purchaseOrders:[]
        },
        th:0,
        tableKey:'materialNo',
        list:[],
        columns:[
          { title: '序号', key: 'index', width: 70, align:'center', scopedSlots: { customRender: 'index' }},
          { title: '物料编码', dataIndex: 'materialNo', key: 'materialNo' },
          { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
          { title: '规格', dataIndex: 'materialSpec', key: 'materialSpec' },
          { title: '单位类型', dataIndex: 'basicUnit', key: 'basicUnit', width: 120, scopedSlots: { customRender: 'unitTyleSlot' }},
          { title: '送货数', dataIndex: 'deliverQuantity', key: 'deliverQuantity', width: 180 }
        ],
        columnA:{ title: '操作', key: 'action', width: 80, align:'center', fixed:"right", scopedSlots: { customRender: 'action' }},
        columnB:{ title: '收货数', key: 'receiveQuantity', scopedSlots: { customRender: 'inputCell' }, width: 220, align:'center'},
        columnsAdd:[],
        columnsEdit:[],
        chooseVisible:false,
        chooseOrderNo:''
      }
    },
    methods: {
      // 初始化方法
      init (record) {
        this.visible = true
        this.$nextTick(() => {
          this.th = this.$refs.listWrapper.clientHeight - 60
          if (this.type==='modify') {
            let _arr = [...this.columns]
            _arr.push(this.columnB)
            this.columnsEdit = _arr
            this.getEditInitData(record)
          } else {
            let _arr = [...this.columns]
            _arr.push(this.columnA)
            this.columnsAdd = _arr
            this.getAddInitData()
          }
        });
      },
      getAddInitData(){
        this.confirmLoading = true;
        Promise.all([
          GetBillNumber(),
          GetPurchaseOrders()
        ]).then(response=>{
          let formData = {
            purchaseReceiveOrderOrderNo:(response[0].data.orderNo || '')
          }
          this.selectOptions.purchaseOrders = response[1].data || []
          if (this.selectOptions.purchaseOrders.length===1){
            formData.purchaseOrderNo = this.selectOptions.purchaseOrders[0].purchaseOrderNo
          }
          this.form.setFieldsValue(formData)
          this.confirmLoading = false;
        }).catch((err)=>{
          this.confirmLoading = false;
        })
      },
      getEditInitData(record){
        let formData = {
          purchaseReceiveOrderOrderNo:record.orderNo,
          purchaseOrderNo:record.receiveOrderNo
        }
        this.form.setFieldsValue(formData)
        this.confirmLoading = true;
        let params = {
          Id:record.id,
          PageNo:1,
          PageSize:999
        }
        PurchaseReceiveOrderDetailPage(params).then((d)=>{
          this.list = d.data.rows || []
          this.confirmLoading = false;
        }).catch(()=>{
          this.confirmLoading = false;
        })
      },
      chooseBack(arr){
        let newArr = [], reCount = 0;
        arr.forEach((item)=>{
          let f = false;
          for (let i=0;i<this.list.length;i++) {
            if (this.list[i][this.tableKey] === item[this.tableKey]) {
              reCount++;
              f = true
              break;
            }
          }
          if (!f) {
            let _obj = {...item}
            _obj.orderQuantity = 0
            _obj.requireTime = ''
            newArr.push(item)
          }
        })
        this.list = [].concat(newArr,this.list)
        if (reCount) {
          this.$message.warning(`${reCount}笔数据已存在，未添加！`);
        }
      },
      cancelListItem(index){
        this.list.splice(index,1)
      },
      interalNumberValidate(val){
        let res = 0
        if (!val) {
          res = 1  //数量必填且大于0
        } else if (Number(val)!==parseInt(val)) {
          res = 2  //只能是整数
        }
        return res
      },
      checkBeforeSubmit() {
        let res = true, msg = '';
        if (this.type==='modify') {
          for (let i=0;i<this.list.length;i++) {
            let numberTag = this.interalNumberValidate(this.list[i].receiveQuantity)
            if (numberTag!==0) {
              res = false
              if (numberTag===1) {
                msg = `第${i+1}行，收货数必填且大于0！`
              } else if (numberTag===2) {
                msg = `第${i+1}行，收货数只能是整数！`
              }
              break;
            }
          }
        }
        if (!res) {
          this.$message.warning(msg);
        }
        return res
      },
      /**
       * 提交表单
       */
      onSubmit () {
        const { form: { validateFields } } = this
        validateFields((errors, values) => {
          if (!errors) {
            let f = this.checkBeforeSubmit()
            if (f) {
              this.confirmLoading = true
              this.handleSubmit(values,(fx)=>{
                if (fx) {
                  this.$message.success('提交成功')
                  this.confirmLoading = false
                  this.handleCancel()
                  this.$emit('ok')
                } else {
                  this.confirmLoading = false
                }
              })
            }
          } 
        })
      },
      handleSubmit(values,callback){
        this.confirmLoading = true
        if (this.type==='modify') {
          this.handleSubmitModify(callback)
        } else {
          this.handleSubmitAdd(values,callback)
        }
      },
      handleSubmitAdd(values,callback){
        let params = {...values,...{purchaseReceiveOrderDetailList:this.list}}
        PurchaseReceiveOrderAdd(params).then(()=>{
          callback && callback(true)
        }).catch(()=>{
          callback && callback(false)
        })
      },
      handleSubmitModify(callback){
        let params = [...this.list]
        PurchaseReceiveOrderEditDetailNumber(params).then(()=>{
          callback && callback(true)
        }).catch(()=>{
          callback && callback(false)
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.list = []
        this.visible = false
      },
      openChoose(){
        this.form.validateFields(['purchaseOrderNo'],(errors, values) =>{
          if (!errors){
            this.chooseOrderNo = values.purchaseOrderNo
            this.chooseVisible = true
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
.purchase-receive-modal-content{
  height: 70vh;
  display: flex;
  flex-direction: column;
  .form-view,.action-view{
    flex-shrink: 0;
  }
  .form-view{
    background-color: #F3F7FA;
    padding-top: 20px;
  }
  .action-view{
    padding: 8px 16px;
  }
  .list-view{
    flex-grow: 1;
    padding: 0 16px;
    overflow: auto;
  }
}
</style>
